<template>
  <div class="region-map-chart">
    <div class="chart-controls" v-if="showControls">
      <el-radio-group v-model="activeDimension" size="small" @change="changeDimension">
        <el-radio-button value="companyCount">企业数量</el-radio-button>
        <el-radio-button value="employeeCount">员工数量</el-radio-button>
        <el-radio-button value="registeredCapital">注册资本</el-radio-button>
        <el-radio-button value="highTechCount">高新数量</el-radio-button>
      </el-radio-group>
    </div>
    <div ref="chartContainer" class="chart-container"></div>
    <div v-if="!hasValidData" class="no-data-tip">暂无数据</div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import chinaMap from '@/assets/china-map.json';

export default {
  name: 'RegionMapChart',
  props: {
    data: {
      type: Array,
      required: true
    },
    dimension: {
      type: String,
      default: 'companyCount'
    },
    showControls: {
      type: Boolean,
      default: true
    }
  },
  emits: ['dimensionChange'],
  setup(props, { emit }) {
    const chartContainer = ref(null);
    let chartInstance = null;
    const activeDimension = ref(props.dimension);
    const hasValidData = ref(false);

    // 维度标题映射
    const dimensionTitles = {
      companyCount: '企业数量分布',
      employeeCount: '员工数量分布',
      registeredCapital: '注册资本分布',
      highTechCount: '高新企业分布'
    };

    // 初始化图表
    const initChart = () => {
      if (!chartContainer.value) {
        console.error('图表容器不存在');
        return;
      }
      
      try {
        // 销毁之前的实例
        if (chartInstance) {
          chartInstance.dispose();
        }
        
        // 创建新的实例
        chartInstance = echarts.init(chartContainer.value);
        console.log('地图图表实例已创建');
        
        // 注册中国地图
        echarts.registerMap('china', chinaMap);
        console.log('中国地图已注册');
        
        // 渲染地图
        renderMap();
      } catch (error) {
        console.error('初始化地图图表失败:', error);
        ElMessage.error('初始化地图图表失败');
      }
    };

    // 渲染地图
    const renderMap = () => {
      if (!chartInstance) {
        console.error('图表实例不存在');
        return;
      }

      if (!props.data || !props.data.length) {
        console.warn('地图数据为空');
        hasValidData.value = false;
        chartInstance.setOption({
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'center',
            textStyle: {
              fontSize: 16,
              color: '#909399'
            }
          }
        });
        return;
      }

      try {
        console.log('开始处理地图数据', props.data);
        
        const dimensionKey = activeDimension.value;
        const mapData = [];
        
        // 处理地图数据
        props.data.forEach(item => {
          if (!item || !item.province) return;
          
          // 获取省份名称
          const provinceName = item.province;
          
          // 获取对应维度的值
          let value = 0;
          if (typeof item[dimensionKey] === 'number') {
            value = item[dimensionKey];
          } else if (typeof item[dimensionKey] === 'string' && !isNaN(parseFloat(item[dimensionKey]))) {
            value = parseFloat(item[dimensionKey]);
          }
          
          mapData.push({
            name: provinceName,
            value: value
          });
        });
        
        if (mapData.length === 0) {
          console.warn('处理后的地图数据为空');
          hasValidData.value = false;
          chartInstance.setOption({
            title: {
              text: '暂无有效数据',
              left: 'center',
              top: 'center',
              textStyle: {
                fontSize: 16,
                color: '#909399'
              }
            }
          });
          return;
        }
        
        console.log('处理后的地图数据:', mapData);
        hasValidData.value = true;
        
        // 计算最大值，用于可视化映射
        const maxValue = Math.max(...mapData.map(item => item.value || 0));
        
        // 设置地图选项
        const option = {
          title: {
            text: dimensionTitles[dimensionKey] || '数据分布',
            left: 'center',
            textStyle: {
              fontSize: 16,
              fontWeight: 'normal'
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c}'
          },
          visualMap: {
            min: 0,
            max: maxValue > 0 ? maxValue : 100,
            left: 'left',
            top: 'bottom',
            text: ['高', '低'],
            calculable: true,
            inRange: {
              color: ['#e0f3f8', '#aadbf0', '#67c3e0', '#419acc', '#2070b4', '#0a3a81']
            }
          },
          series: [
            {
              name: dimensionTitles[dimensionKey] || '数据',
              type: 'map',
              map: 'china',
              roam: true,
              label: {
                show: true,
                fontSize: 10
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 12
                },
                itemStyle: {
                  areaColor: '#92d0ea'
                }
              },
              data: mapData
            }
          ]
        };
        
        // 应用选项
        chartInstance.setOption(option, true);
        console.log('地图渲染完成');
        
        // 确保地图完全渲染
        setTimeout(() => {
          chartInstance.resize();
        }, 300);
      } catch (error) {
        console.error('渲染地图失败:', error);
        hasValidData.value = false;
        chartInstance.setOption({
          title: {
            text: '渲染失败',
            left: 'center',
            top: 'center',
            textStyle: {
              fontSize: 16,
              color: '#f56c6c'
            }
          }
        });
      }
    };

    // 切换维度
    const changeDimension = (value) => {
      activeDimension.value = value;
      emit('dimensionChange', value);
      renderMap();
    };

    // 窗口大小变化时重新调整图表大小
    const handleResize = () => {
      if (chartInstance) {
        chartInstance.resize();
      }
    };

    // 监听维度变化
    watch(() => props.dimension, (newValue) => {
      if (newValue !== activeDimension.value) {
        activeDimension.value = newValue;
        renderMap();
      }
    });

    // 监听数据变化
    watch(() => props.data, () => {
      console.log('地图数据变化，重新渲染');
      renderMap();
    }, { deep: true });

    // 生命周期钩子
    onMounted(() => {
      console.log('RegionMapChart组件已挂载');
      initChart();
      window.addEventListener('resize', handleResize);
    });

    onUnmounted(() => {
      console.log('RegionMapChart组件已卸载');
      if (chartInstance) {
        chartInstance.dispose();
        chartInstance = null;
      }
      window.removeEventListener('resize', handleResize);
    });

    return {
      chartContainer,
      activeDimension,
      hasValidData,
      changeDimension
    };
  }
};
</script>

<style scoped>
.region-map-chart {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  position: relative;
}

.chart-controls {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.chart-container {
  width: 100%;
  height: 500px;
}

.no-data-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #909399;
  font-size: 14px;
}
</style> 